package com.yc.services;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.bean.Address;
import com.yc.mapper.AddressMapper;
import com.yc.web.DTO.AddressDTO;
import com.yc.web.clients.IdGeneratorClient;
import com.yc.web.controller.model.ResponseResult;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Log
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;
    private final IdGeneratorClient idGeneratorClient;

    public final static Integer ADDRESS_STATUS_DELETED = 0;
    public final static Integer ADDRESS_STATUS_NORMAL = 1;
    public final static Integer ADDRESS_DEFAULT_YES = 1;
    public final static Integer ADDRESS_DEFAULT_NO = 0;

    /**
     * 新增地址
     * @param addressDTO 地址信息
     * @return 新增的地址DTO
     */
    @Override
    @Transactional
    public AddressDTO addAddress(AddressDTO addressDTO) {
        // 生成地址ID
        ResponseResult rr = this.idGeneratorClient.getNextId();
        if (rr.getCode() != 1) {
            throw new RuntimeException("地址ID生成失败");
        }
        Long addressId = Long.parseLong(rr.getData().toString());
        addressDTO.setAddressId(addressId);

        // 设置默认状态
        if (addressDTO.getAddressStatus() == null) {
            addressDTO.setAddressStatus(ADDRESS_STATUS_NORMAL);
        }
        if (addressDTO.getIsDefault() == null) {
            addressDTO.setIsDefault(ADDRESS_DEFAULT_NO);
        }

        // 将DTO转换为实体
        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);

        // 插入数据库
        int result = this.addressMapper.insert(address);
        if (result > 0) {
            // 如果设置为默认地址，调用单独的方法设置
            if (addressDTO.getIsDefault() == ADDRESS_DEFAULT_YES) {
                this.setDefaultAddress(addressId, addressDTO.getUserId());
            }
            BeanUtils.copyProperties(address, addressDTO);
            return addressDTO;
        } else {
            throw new RuntimeException("新增地址失败");
        }
    }
//    @Transactional
//    public AddressDTO addAddress(AddressDTO addressDTO) {
//        // 1. 生成地址ID
//        ResponseResult rr = this.idGeneratorClient.getNextId();
//        if (rr.getCode() != 1) {
//            throw new RuntimeException("地址ID生成失败");
//        }
//        Long addressId = Long.parseLong(rr.getData().toString());
//        addressDTO.setAddressId(addressId);
//
//        // 2. 如果设置为默认地址，需要先将该用户的其他地址设为非默认
//        // 在 addAddress 方法中替换原有的设置默认地址逻辑
//        if (addressDTO.getIsDefault() != null && addressDTO.getIsDefault() == ADDRESS_DEFAULT_YES) {
//            this.setDefaultAddress(addressId, addressDTO.getUserId());
//        }
//
//        // 3. 设置默认状态
//        if (addressDTO.getAddressStatus() == null) {
//            addressDTO.setAddressStatus(ADDRESS_STATUS_NORMAL);
//        }
//        if (addressDTO.getIsDefault() == null) {
//            addressDTO.setIsDefault(ADDRESS_DEFAULT_NO);
//        }
//
//        // 4. 将DTO转换为实体
//        Address address = new Address();
//        BeanUtils.copyProperties(addressDTO, address);
//
//        // 5. 插入数据库
//        int result = this.addressMapper.insert(address);
//        if (result > 0) {
//            // 插入成功后，返回包含完整信息的DTO
//            BeanUtils.copyProperties(address, addressDTO);
//            return addressDTO;
//        } else {
//            throw new RuntimeException("新增地址失败");
//        }
//    }

    /**
     * 更新地址
     * @param addressDTO 地址信息
     * @return 更新后的地址DTO
     */
    @Override
    @Transactional
    public AddressDTO updateAddress(AddressDTO addressDTO) {
        // 1. 检查地址是否存在
        Address existingAddress = addressMapper.selectById(addressDTO.getAddressId());
        if (existingAddress == null) {
            throw new RuntimeException("地址不存在");
        }

        // 2. 如果设置为默认地址，需要先将该用户的其他地址设为非默认
        // 在 updateAddress 方法中替换原有的设置默认地址逻辑
        if (addressDTO.getIsDefault() != null && addressDTO.getIsDefault() == ADDRESS_DEFAULT_YES) {
            this.setDefaultAddress(addressDTO.getAddressId(), existingAddress.getUserId());
        }

        // 3. 更新地址信息
        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        int result = this.addressMapper.updateById(address);
        if (result > 0) {
            // 更新成功后，返回包含完整信息的DTO
            BeanUtils.copyProperties(address, addressDTO);
            return addressDTO;
        } else {
            throw new RuntimeException("更新地址失败");
        }
    }

    /**
     * 删除地址（逻辑删除）
     * @param addressId 地址ID
     * @param userId 用户ID
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public boolean deleteAddress(Long addressId, Long userId) {
        // 逻辑删除，修改状态为已删除
        Address address = new Address();
        address.setAddressId(addressId);
        address.setAddressStatus(ADDRESS_STATUS_DELETED);

        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getAddressId, addressId)
                .eq(Address::getUserId, userId);

        int result = addressMapper.update(address, wrapper);
        return result > 0;
    }

    /**
     * 获取用户地址列表
     * @param userId 用户ID
     * @return 地址DTO列表
     */
    @Override
    public List<AddressDTO> getUserAddresses(Long userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId)
                .eq(Address::getAddressStatus, ADDRESS_STATUS_NORMAL)
                .orderByDesc(Address::getIsDefault); // 默认地址排前面

        List<Address> addresses = this.addressMapper.selectList(queryWrapper);
        return addresses.stream()
                .map(address -> {
                    AddressDTO dto = new AddressDTO();
                    BeanUtils.copyProperties(address, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取地址详情
     * @param addressId 地址ID
     * @param userId 用户ID
     * @return 地址DTO
     */
    @Override
    public AddressDTO getAddressDetail(Long addressId, Long userId) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getAddressId, addressId)
                .eq(Address::getUserId, userId)
                .eq(Address::getAddressStatus, ADDRESS_STATUS_NORMAL);

        Address address = addressMapper.selectOne(wrapper);
        if (address == null) {
            return null;
        }

        AddressDTO dto = new AddressDTO();
        BeanUtils.copyProperties(address, dto);
        return dto;
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Long addressId, Long userId) {
        // 1. 检查地址是否存在且属于该用户
        LambdaQueryWrapper<Address> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(Address::getAddressId, addressId)
                .eq(Address::getUserId, userId)
                .eq(Address::getAddressStatus, ADDRESS_STATUS_NORMAL);

        Address targetAddress = addressMapper.selectOne(checkWrapper);
        if (targetAddress == null) {
            throw new RuntimeException("地址不存在或不属于该用户");
        }

        // 2. 如果已经是默认地址，直接返回成功
        if (targetAddress.getIsDefault() == ADDRESS_DEFAULT_YES) {
            return true;
        }

        // 3. 将该用户的其他地址设为非默认
        LambdaQueryWrapper<Address> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Address::getUserId, userId);

        Address updateAddress = new Address();
        updateAddress.setIsDefault(ADDRESS_DEFAULT_NO);
        addressMapper.update(updateAddress, updateWrapper);

        // 4. 将指定地址设为默认
        Address newDefaultAddress = new Address();
        newDefaultAddress.setAddressId(addressId);
        newDefaultAddress.setIsDefault(ADDRESS_DEFAULT_YES);

        int result = addressMapper.updateById(newDefaultAddress);
        return result > 0;
    }

    @Override
    public Long getDefaultAddressId(Long userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId)
                .eq(Address::getAddressStatus, ADDRESS_STATUS_NORMAL)
                .eq(Address::getIsDefault, ADDRESS_DEFAULT_YES)
                .select(Address::getAddressId); // 只查询addressId字段提高效率

        Address address = addressMapper.selectOne(queryWrapper);
        return address != null ? address.getAddressId() : null;
    }

}